package com.example.interceptor;

import com.example.util.CurrentHolder;
import com.example.util.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1. 获取请求URL
        String url = request.getRequestURL().toString();
        // 2. 判断是否是login
        if (url.contains("login")) {
            log.info("登录请求，直接放行");
            return true;
        }
        // 3. 获取请求头的令牌
        String token = request.getHeader("token");
        // 4.判断token是否存在
        if(!StringUtils.hasLength(token)) {
            log.info("jwt令牌为空，返回错误");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        // 5. 不为空则解析
        try {
            Claims claims = jwtUtil.parseToken(token);
            Integer empId = Integer.valueOf(claims.get("id").toString());
            CurrentHolder.setCurrentHolder(empId);
            log.info("登录信息已被保存到ThreadLocal：{}", CurrentHolder.getCurrentHolder());
        } catch (Exception e) {
            e.printStackTrace();
            log.info("令牌解析失败，返回错误");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        // 6. 解析令牌成功，放行
        log.info("令牌解析成功，放行");
        return true;
    }
}
